﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Ranet.Web.Olap;
using Ranet.Olap.Core.Data;
using Galaktika.BI.Silverlight.ClientApp.Web.Runtime.Services;
using Microsoft.AnalysisServices.AdomdClient;
using Ranet.Olap.Core;
using Ranet.Olap.Core.Providers;

namespace Galaktika.BI.Silverlight.ClientApp.Web
{
    public class MDXQueryExecuter : IQueryExecuter
    {
        public MDXQueryExecuter(ConnectionInfo connection)
        {
            if (connection == null)
                throw new ArgumentNullException("connection");
            m_Connection = connection;
        }

        #region IQueryExecuter Members
        ConnectionInfo m_Connection = null;
        public ConnectionInfo Connection
        {
            get
            {
                if (m_Connection == null)
                    m_Connection = new ConnectionInfo();
                return m_Connection;
            }
        }

        public CellSetData ExecuteQuery(string query)
        {
            string parsedConnStr = Connection.ConnectionString;
            string parsedQuery = query;

            AdomdConnection conn = AdomdConnectionPool.GetConnection(parsedConnStr);
            using (AdomdCommand cmd = new AdomdCommand(parsedQuery, conn))
            {
                CellSet cs = cmd.ExecuteCellSet();

                CellSetDescriptionProvider provider = new CellSetDescriptionProvider(cs);
                provider.CellSet.Connection = Connection;
                if (cs.OlapInfo != null &&
                    cs.OlapInfo.CubeInfo != null &&
                    cs.OlapInfo.CubeInfo.Cubes != null &&
                    cs.OlapInfo.CubeInfo.Cubes.Count > 0)
                {
                    provider.CellSet.CubeName = cs.OlapInfo.CubeInfo.Cubes[0].CubeName;
                }

                return provider.CellSet;
            }
        }

        public int ExecuteNonQuery(string query)
        {
            string parsedConnStr = Connection.ConnectionString;
            string parsedQuery = query;

            AdomdConnection conn = AdomdConnectionPool.GetConnection(parsedConnStr);
            using (AdomdCommand cmd = new AdomdCommand(parsedQuery, conn))
            {
                return cmd.ExecuteNonQuery();
            }
        }
        #endregion
    }
}
